/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number[]} voyage
 * @return {number[]}
 */
var flipMatchVoyage = function (root, voyage) {
  let ret = [];
  let i = 0;
  if (root.val !== voyage[i]) {
    return [-1];
  }
  const bst = (node) => {
    if (!node) {
      return;
    }
    i++;
    if (node.left && node.left.val === voyage[i]) {
      bst(node.left);
    }

    if (node.right && node.right.val === voyage[i]) {
      bst(node.right);
      // 发生翻转
      // 如果左节点发生异常，依然不匹配，那么i就不会继续前进，所以只需要最后比较i和voyage的长度，善于跳出思维
      if (node.left && node.left.val === voyage[i]) {
        ret.push(node.val);
        bst(node.left);
      }
    }
  };
  bst(root);
  return i === voyage.length ? ret : [-1];
};
